from django.utils.deprecation import MiddlewareMixin
from .models import Data_date, Access_ip
import datetime

class Access_ipMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 避免递归调用 - 检查是否是内部请求
        if hasattr(request, '_access_ip_processed'):
            return None
        
        try:
            request._access_ip_processed = True
            
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            
            # 验证IP地址 - 允许所有有效IP包括127.0.0.1
            if not ip:
                return None
                
            today = datetime.date.today()
            date, created = Data_date.objects.get_or_create(date=today)
            Access_ip.objects.create(ip_address=ip, date=date)
            
        except Exception as e:
            # 记录错误但不中断请求处理
            print(f"Access_ipMiddleware error: {e}")
            pass
            
        return None